package bean.managed;

import bean.session.SystemUserEntityFacade;
import entity.InternalMessageEntity;
import entity.InternalMessageReceivedEntity;
import java.io.*;
import java.util.HashMap;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.primefaces.event.TabChangeEvent;
import type.MessageType;

@ManagedBean(name = "announcementController")
@SessionScoped
public class AnnouncementController extends UserMessageController implements Serializable {

    private String redirectLink = "/entities/internalMessageEntity/Announcement.xhtml?faces-redirect=true";
    private String viewLink = "/entities/internalMessageEntity/ViewAnnouncement.xhtml?faces-redirect=true";

    public void populateInbox() {
        if(getCurrentUser()==null)
            return;
        
        current = null;
        messageType = MessageType.Announcement;
        userManagedBean.isDisplayAnnoucementInbox();
        msg = userManagedBean.getAnnouncementInbox();
        markMessagesReadUnread();
        System.out.println("Announcement: populate inbox");
    }

    public void action(TabChangeEvent event) {
        String folderName = event.getTab().getId();
        System.out.println("Accessing Folder: " + folderName);
        msgToUserInstance = new HashMap<InternalMessageEntity, InternalMessageReceivedEntity>();

        if (folderName.equals("inbox")) {
            populateInbox();
        }

        if (folderName.equals("sent")) {
            current = null;
            userManagedBean.isDisplayAnnoucementSent();
            msg = userManagedBean.getAnnouncementSent();
        }

        if (folderName.equals("drafts")) {
            current = null;
            userManagedBean.isDisplayAnnouncementDraft();
            msg = userManagedBean.getAnnouncementDraft();
        }

        setStatus("");
    }

    public String createOrUpdateAnnouncement() {
        current.setMessageType(MessageType.Announcement);
        if (current.getId() != null) {
            return update();
        } else {
            return create();
        }
    }

    public String createOrUpdateAnnouncementAndSend() {
        current.setMessageType(MessageType.Announcement);
        if (current.getId() != null) {
            return updateAndSend();
        } else {
            return createAndSend();
        }
    }

    public String draftSelect() {
        System.out.println("Opening Saved Draft: " + selectedMessage);
        current = selectedMessage;
        setTabIndex(0);
        return getRedirectLink();
    }

    public void setUserBean(SystemUserEntityFacade userBean) {
        this.userBean = userBean;
    }

    public String getRedirectLink() {
        return redirectLink;
    }

    public void setRedirectLink(String redirectLink) {
        this.redirectLink = redirectLink;
    }

    public String getViewLink() {
        return viewLink;
    }

    public void setViewLink(String viewLink) {
        this.viewLink = viewLink;
    }
}
